<template>
    <!--左侧房源筛选-->
    <div class="lefMain" v-show="!isFastSearch">
        <!--左侧1-->
        <span class="leftTop">
            <span style="font-size: 18px;white-space: nowrap;font-weight: 600;color: #7a8df1;">{{
                $t('text.DialogLayout.l211') }}</span>
            <DialogLayout21>
                <span class="df" @click="isShowAddHouse">
                    <img class="addImg" src="../../assets/images/add.svg">
                    <div style="font-size: 13px;white-space: nowrap;">{{ $t('text.House.l183') }}</div>
                </span>
            </DialogLayout21>
        </span>

        <!--左侧2-->
        <div class="leftTopInput">
            <img class="img1" src="../../assets/images/search2.png" />
            <input :placeholder="$t('text.Customer.l15')" class="leftTop2Input" v-model="nameOrPhoneOrId"
                @focus="isSearchClick = true">
            <div class="searchDiv4" v-if="isSearchClick" @click="searchClick">{{ $t('text.House.l299') }}</div>
            <span v-if="isSearchClick" @click="isSearchClick = false; nameOrPhoneOrId = ''" class="searchCancel">{{
                $t('text.House.l300')
            }}</span>
        </div>

        <!--模糊搜索列表搜索-->
        <div v-if="isSearchClick && nameOrPhoneOrId != ''">
            <div v-for="item in community" v-bind:key="item" class="searchDiv1">
                <img class="searchDiv2" src="../../assets/images/search2.png" />
                <div style="flex: 1;" @click="nameOrPhoneOrId = item.customerName; searchClick()">
                    <div>{{ item.customerName }}</div>
                    <div class="searchDiv3">NO.{{ item.id }}</div>
                </div>
            </div>
        </div>

        <!--历史搜索-->
        <div v-if="isSearchClick && nameOrPhoneOrId == ''">
            <div class="searchDiv5">{{ $t('text.House.l301') }}</div>
            <div v-for="item in communityLocal" v-bind:key="item" class="searchDiv1" style="gap:5px">
                <div style="flex: 1;" @click="nameOrPhoneOrId = item.customerName; searchClick()">
                    <div>{{ item.customerName }}</div>
                    <div class="searchDiv3"></div>
                </div>
            </div>
        </div>

        <!--左侧3-->
        <div v-if="isLoad && !isSearchClick">
            <div class="leftTop2" v-for="(item, index1) in houseSelect" v-bind:key="item">
                <div class="df" v-for="(s, index2) in item" v-bind:key="s">
                    <img class="img2" src="../../assets/images/icon.png" />
                    <div class="items">
                        <RadioSelect :leftText="s.title" :selectList="s.isArea ? areaList : getSelectData(s.dictionaryKey)"
                            :searchKey="s.searchKey" :isShowTitle="s.isShowTitle" :isShowSerach1="s.isShowSerach1"
                            :isShowSerach2="s.isShowSerach2" :inputEndText="s.inputEndText" :isReset="isReset"
                            :isShowBottom="s.isShowBottom" :isMultiple="s.isMultiple" @returnData="setData" :max="s.max"
                            :min="s.min" @clearData="clearData" :isCustomer="s.isCustomer" :fastSearch="s.fastSearch"
                            :isRange="s.isRange" :orgTreeList="orgTreeList" :isSingle="s.isSingle" :isArea="s.isArea"
                            :ref="'RadioSelect' + index1 + index2">
                        </RadioSelect>
                    </div>
                </div>
            </div>
        </div>

        <!--左侧4-->
        <div class="lb" v-if="!isSearchClick">
            <div class="lb-f">
                <span class="sl-l" @click="openFastSearch">{{ $t('text.House.l167') }}</span>
                <DialogLayout20 :paramJson="searchData" :moduleType="searchData.customerClass + 3"
                    :type="String(searchData.customerClass)" :fastSearchList="fastSearchList">
                    <span @click="getReturnFastSearch">{{ $t('text.House.l168') }}</span>
                </DialogLayout20>
            </div>
            <div class="lb-r" @click="reset">
                <span>{{ $t('text.House.l169') }}</span>
            </div>
        </div>

    </div>

    <!--左侧保存搜索-->
    <div class="lefMain" v-show="isFastSearch && isLoad">
        <div class="s8">
            <div class="s2" v-for="item in fastSearchConvert" v-bind:key="item" @click="setFastSearch(item.paramJson)">
                <div class="s3">
                    <div class="s4">{{ item.title }}&ensp;</div>
                    <div class="s5" @click="deleteFastSearch(item.id)"><img src="../../assets/images/mClose.svg" class="s6">
                    </div>
                </div>
                <div style="height: inherit;overflow: auto;">
                    <div class="s7" v-for="child in JSON.parse(item.paramJson).original" v-bind:key="child">
                        {{ child.title + ": " + child.value }}
                    </div>
                </div>
            </div>
        </div>
        <button class="s1" @click="isFastSearch = !isFastSearch">{{ $t('text.House.l204') }}</button>
    </div>


    <!--右侧房源列表-->
    <div class="rightMain">
        <!--右侧顶部导航-->
        <div class="rightTop">
            <div class="mapDiv f1">
            </div>

            <TimePageNavList :timeNavList="timeNavList.data" :defaultClick="timeNavList.defaultClick"
                @returnData="setHouseType"></TimePageNavList>

            <div class="f1" style="display: flex;justify-content: flex-end;">
                <CommonSelectRouter :dataList="sortRouterList.data" :default="sortRouterList.default" ref="child1"
                    :myStyles="{ width: 'auto', background: 'none' }" @returnData="setSort" isShowSortImg>
                </CommonSelectRouter>
            </div>
        </div>
        <!--右侧房源数据列表-->
        <div class="rightContain">
            <HouseList2 :data="houseList" :typeIndex="searchData.customerClass" :index="searchData.customerClass">
            </HouseList2>

            <!--底部分页-->
            <div class="setPage">
                <el-pagination v-model:current-page="searchData.page" v-model:page-size="searchData.size"
                    :page-sizes="[10, 15, 20, 30, 50]" layout="total, sizes, prev, pager, next, jumper" :total="total"
                    @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

    </div>
</template>
    
<script>
import { customerSelect1, customerSelect2 } from '../../itemList';
import RadioSelect from '../../components/select/RadioSelect.vue'
import { findPageByParam2, getDropdownBoxData2, searchFindPage, searchDel, areaFindTreeAll, orgTreeByCurrUser, findLikeNameOrPhone } from '../../http/api';
import { ElMessage } from 'element-plus'
import DialogLayout21 from '@/components/dialogLayout/DialogLayout21.vue';
import DialogLayout20 from '@/components/dialogLayout/DialogLayout20.vue';
import TimePageNavList from '@/components/navigation/TimePageNavList.vue';
import CommonSelectRouter from '@/components/input/CommonSelectRouter.vue';
import HouseList2 from '@/components/houseList/HouseList2.vue';
export default {
    name: 'CustomManage',
    components: {
        RadioSelect,
        DialogLayout21,
        DialogLayout20,
        TimePageNavList,
        CommonSelectRouter,
        HouseList2
    },
    data() {
        return {
            timeNavList: {
                defaultClick: this.$t('text.House.l177'), data: [this.$t('text.House.l177'), this.$t('text.House.l178')]
            },
            houseSelect: customerSelect1,
            sortRouterList: {
                default: this.$t("text.House.l179"),
                data: [
                    { id: 1, name: this.$t("text.House.l179") },
                    { id: 2, name: this.$t("text.House.l180") },
                    { id: 3, name: this.$t("text.House.l181") },
                    { id: 4, name: this.$t("text.House.l182") },
                ]
            },
            searchData: {
                customerClass: 0,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 10
            },
            searchDataDefault: {
                customerClass: 0,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 10
            },
            isLoad: false,
            loadCount: 0,
            dictionaryTree: {},
            isReset: false,
            houseList: [],
            total: 0,
            isFastSearch: false,
            fastSearchList: [],
            fastSearchConvert: [],
            areaList: [],
            orgTreeList: [],
            nameOrPhoneOrId: "",
            isSearchClick: false,
            community: [],
            communityLocal: [],
            communityCopy: []
        }
    },
    mounted() {
        //初始化查询
        this.search()
        this.loadCount = 0
        //初始化字典数据请求
        getDropdownBoxData2().then(res => {
            console.log(res)
            if (res !== undefined) {
                this.dictionaryTree = res

                areaFindTreeAll().then(res => {
                    if (res !== undefined) {
                        this.areaList = [{dictName: this.$t('text.Common.l12'),dictValue: "-1"},...res]
                        this.loadCount = this.loadCount + 1
                    }
                }).catch()

                orgTreeByCurrUser().then(res => {
                    if (res !== undefined) {
                        this.orgTreeList = res
                        this.loadCount = this.loadCount + 1
                    }
                }).catch()

            }
        }).catch()

    },
    methods: {

        //获取字典数据
        getSelectData(key) {
            const data = this.dictionaryTree[key]
            if (data != undefined) {
                return this.dictionaryTree[key]
            } else {
                return [{
                    "dictName": "不限",
                    "dictValue": "-1",
                },]
            }
        },

        //拼接单个子组件返回来的条件值
        setData(obj) {
            this.searchData = { ...this.searchData, ...obj }
            console.log(JSON.stringify(this.searchData))
        },



        //子组件选择了不限，进行删除指定字段
        clearData(obj) {
            const objKeys = Object.keys(obj);
            this.searchData = Object.keys(this.searchData).reduce((acc, key) => {
                if (!objKeys.includes(key)) {
                    acc[key] = this.searchData[key];
                }
                return acc;
            }, {});
            console.log(JSON.stringify(this.searchData))
        },

        //清除只返回值
        clearData2(obj) {
            const objKeys = Object.keys(obj);
            return Object.keys(this.searchData).reduce((acc, key) => {
                if (!objKeys.includes(key)) {
                    acc[key] = this.searchData[key];
                }
                return acc;
            }, {});
        },


        //打开快速搜索
        openFastSearch() {
            searchFindPage({ moduleType: this.searchData.customerClass + 3 }).then((res) => {
                if (res !== undefined) {
                    this.fastSearchConvert = res
                    this.isFastSearch = !this.isFastSearch
                }
            }).catch()
        },

        //获取查询列表改动的标题和显示值
        getReturnFastSearch() {
            let temp = []
            this.houseSelect.forEach((element, index1) => {
                element.forEach((item, index2) => {
                    const childRef = this.$refs['RadioSelect' + index1 + index2]
                    if (childRef && childRef.length > 0 && childRef[0].returnFastSearch() != null) {
                        temp.push(childRef[0].returnFastSearch())
                    }
                });
            });
            this.fastSearchList = temp
            console.log(this.fastSearchList)
            return temp
        },

        //保存搜索里面，根据快速搜索取出来的值进行匹配赋值,
        setFastSearch(obj) {
            obj = JSON.parse(obj)
            let select = JSON.parse(JSON.stringify(this.houseSelect))
            select.forEach(element => {
                element.forEach(element2 => {
                    const temp = obj.original.filter(v => v.searchKey === element2.searchKey)
                    if (temp.length > 0)
                    element2.fastSearch = temp[0].value
                });
            });
            this.houseSelect = select
            this.isFastSearch = !this.isFastSearch
            this.searchData = obj.params
        },

        //删除快速保存
        deleteFastSearch(id) {
            searchDel({ id: id }).then(res => {
                if (res !== undefined) {
                    ElMessage.success({
                        showClose: true,
                        message: this.$t('text.House.l206'),
                        type: 'success',
                    })
                } else {
                    ElMessage.error({
                        showClose: true,
                        message: this.$t('text.House.l205'),
                        type: 'error',
                    })
                }
            }).catch()
        },

        //选择排序
        setSort(index) {
            // this.$nextTick(() => {
            //     this.clearData({ customerTime_ORDER: '', followTime_ORDER: '', leadWatchCount_ORDER: '' })
            // })
            let obj
            switch (index) {
                case 1: obj = { customerTime_ORDER: "DESC" }; break;
                case 2: obj = { followTime_ORDER: "DESC" }; break;
                case 3: obj = { leadWatchCount_ORDER: "DESC" }; break;
                case 4: obj = { leadWatchCount_ORDER: "ASC" }; break;
            }
            this.searchData = { ...this.clearData2({ customerTime_ORDER: '', followTime_ORDER: '', leadWatchCount_ORDER: '' }), ...obj }
        },

        //切换房屋类型
        setHouseType(index) {
            let temp
            switch (index) {
                case 0: temp = { customerClass: 0 }; this.searchData = { ...this.searchDataDefault, ...temp }; this.houseSelect = customerSelect1; break;
                case 1: temp = { customerClass: 1 }; this.searchData = { ...this.searchDataDefault, ...temp }; this.houseSelect = customerSelect2; break;
            }
            this.nameOrPhoneOrId = ""
        },

        //搜索数据
        search() {
            findPageByParam2(this.searchData).then(res => {
                if (res !== undefined) {
                    this.houseList = res.dataList
                    this.total = res.total
                    console.log(res)
                }
            }).catch()
        },

        //重置
        reset() {
            this.searchData = {
                customerClass: this.searchData.customerClass,
                label: null,
                role: null,
                roomNumber: null,
                page: 1,
                size: 10
            }
            this.isReset = !this.isReset
        },
        handleSizeChange(val) {
            this.searchData.size = val
            this.search()
        },
        handleCurrentChange(val) {
            this.searchData.page = val
            this.search()
        },
        //点击顶部搜索
        searchClick() {
            if (this.nameOrPhoneOrId != "") {
                let obj = { nameOrPhoneOrId: this.nameOrPhoneOrId }
                this.setData(obj)
                let records = JSON.parse(localStorage.getItem("nameOrPhoneOrId")) || [];
                // 添加新记录到数组开头
                records.unshift({ customerName: this.nameOrPhoneOrId });
                // 如果记录数超过 20 个，删除最旧的记录
                if (records.length > 20) {
                    records.pop();
                }
                // 保存更新后的记录数组到 localStorage
                localStorage.setItem("nameOrPhoneOrId", JSON.stringify(records));

            }
            this.isSearchClick = !this.isSearchClick
        }

    },
    watch: {
        searchData: {
            handler() {
                this.search()
            }
        },
        loadCount: {
            handler() {
                if (this.loadCount >= 2) {
                    this.isLoad = true
                }
            }
        },
        //监听最顶部搜素框的值
        nameOrPhoneOrId() {
            if (this.nameOrPhoneOrId != "" && this.communityCopy.length == 0) {
                //相当于初始化，只有打开点击输入了才请求一次
                findLikeNameOrPhone().then(res => {
                    if (res !== undefined) {
                        console.log("findLikeNameOrPhone", res)
                        this.communityCopy = res
                        this.community = res.filter(v => v.customerName.includes(this.nameOrPhoneOrId) || v.customerPhone.includes(this.nameOrPhoneOrId) || v.id.includes(this.nameOrPhoneOrId))
                    }
                }).catch()
            }
            if (this.nameOrPhoneOrId != "") {
                //模糊匹配过滤
                this.community = this.communityCopy.filter(v => v.customerName.includes(this.nameOrPhoneOrId) || v.customerPhone.includes(this.nameOrPhoneOrId) || v.id.includes(this.nameOrPhoneOrId))
            }
            if (this.nameOrPhoneOrId == "") {
                this.clearData({ nameOrPhoneOrId: "" })
            }
        },
        isSearchClick() {
            //获取缓存
            let records = JSON.parse(localStorage.getItem("nameOrPhoneOrId")) || [];
            this.communityLocal = records
        }
    },
    computed: {

    }

}
</script>
    
<style scoped>
.searchDiv5 {
    text-align: left;
    font-size: 14px;
    color: gray;
    padding: 5px;
}

.searchDiv4 {
    display: flex;
    z-index: 2;
    font-size: 12px;
    color: #6698ff;
    white-space: nowrap;
    padding-top: 6px;
    padding-left: 10px;
}

.searchDiv3 {
    color: #b0b0b0;
    border-bottom: 1px solid #eee;
    padding-bottom: 3px;
}

.searchDiv2 {
    width: 15px;
    height: 15px;
    z-index: 1;
    padding-right: 5px;
}

.searchDiv1 {
    display: flex;
    align-items: center;
    text-align: left;
    padding: 5px 15px;
    font-size: 13px;
}

.searchCancel {
    font-size: 12px;
    color: #6698ff;
    white-space: nowrap;
    padding-top: 6px;
    padding-left: 10px;
}

.df {
    display: flex;
    align-items: center;
    margin-top: 2px;
    margin-bottom: 2px;
}

.lefMain {
    min-width: 310px;
    padding: 15px;
    overflow: auto;
    background: white;
    margin-bottom: 30px;
    margin-right: 5px;
    box-shadow: 1px 10px 30px 4px #e9e9e9;
}

.leftTop {
    color: #6698ff;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.leftTop2 {
    border: 1px solid #cecece;
    border-radius: 5px;
    padding: 10px;
    margin-top: 10px;
    position: relative;
}

.leftTopInput {
    display: flex;
    width: 100%;
    position: relative;
    padding-top: 10px;
}

.leftTop2Input {
    outline: none;
    width: inherit;
    height: 25px;
    border: 1px solid rgb(220, 223, 230);
    padding-left: 23px;
    padding-right: 20px;
    background-color: rgb(242, 242, 242);
    border-radius: 5px;
    font-size: 12px;
    position: relative;
}

.leftTop2Input:focus {
    border: 1px solid #6698ff;
}

.img1 {
    position: absolute;
    left: 7px;
    width: 15px;
    height: 15px;
    top: 17px;
    z-index: 1;
}

.addImg {
    width: 15px;
    height: 15px;
    padding-right: 3px;
}

span {
    font-size: 14px;
}

.mapDiv {
    display: flex;
    padding-left: 15px;
    font-size: 13px;
    color: #6698ff;
    align-items: center;
}

.leftTop2-1 {
    display: flex;
    align-items: center;
    font-size: 12px;
    margin-top: 15px;
    line-height: 18px;
    color: gray;
}

.img2 {
    width: 22px;
    height: 22px;
}

.items {
    margin-left: 15px;
    padding-top: 6px;
    padding-bottom: 6px;
    font-size: 12px;
    color: gray;
    border-bottom: 1px solid rgb(224, 224, 224);
    width: 100%;
}

.lb {
    color: #6698ff;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
    position: absolute;
    bottom: 40px;
    width: 300px;
}

.sl-l::after {
    content: "|";
    padding-left: 5px;
    padding-right: 5px;
}

.rightMain {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f8f8f8;
}

.rightContain {
    display: flex;
    flex-direction: column;
    flex: 1;
    overflow: auto;
    background: white;
    margin: 10px 30px 30px 25px;
    position: relative;
    box-shadow: 1px 5px 10px 4px #e9e9e9;
}

.rightTop {
    display: flex;
    padding-top: 12px;
    align-items: center;
    justify-content: space-between;
    padding-left: 10px;
    padding-right: 17px;
}

.f1 {
    flex: 1;
}

.lb-f {
    display: flex;
    align-items: center;
}

.lb-r {
    position: absolute;
    right: 0;
}

.s1 {
    background: rgb(242, 242, 242);
    border: none;
    outline: none;
    width: 100%;
    padding: 4px 0;
    border-radius: 5px;
    margin: 10px 0;
}

.s1:hover {
    color: #6698ff;
    border: 1px solid #6698ff;
    border-radius: 7px;
}

.s2 {
    border: 1px solid #ddd;
    border-radius: 10px;
    padding: 10px;
    font-size: 12px;
    text-align: left;
    width: 120px;
    height: 150px;
    overflow: hidden;
}

.s3 {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #ddd;
    padding-bottom: 3px;
}

.s6 {
    width: 10px;
    height: 10px;
}

.s6:hover {
    width: 15px;
    height: 15px;
}

.s8 {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.setPage {
    display: flex;
    justify-content: flex-end;
    border-top: 1px solid #eee;
    padding: 10px
}
</style>